package dev.werillib.net

import android.content.Context
import dev.werillib.utils.d
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.concurrent.TimeUnit

/**
 * create by weril 2018/11/27
 */
object NetManager {
    private var retrofit: Retrofit? = null

    fun init(context: Context, baseUrl: String, debugUrl: String, debug: Boolean, vararg interceptor: Interceptor) {
        val loggingInterceptor = HttpLoggingInterceptor()
        loggingInterceptor.level = if (debug) {
            HttpLoggingInterceptor.Level.BODY
        } else {
            HttpLoggingInterceptor.Level.NONE
        }

        val okHttpClient: OkHttpClient = OkHttpClient()
            .newBuilder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(20, TimeUnit.SECONDS)
            .cache(Cache(context.cacheDir, 10 * 1024 * 1024))
            .addInterceptor(loggingInterceptor)
            .apply {
                for (i in interceptor) {
                    this.addInterceptor(i)
                }
            }.build()

        retrofit = Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl(
                if (debug) {
                    debugUrl
                } else {
                    baseUrl
                }
            )
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(MoshiConverterFactory.create())
            .build()
    }

    fun getRetrofit(): Retrofit? {
        if (retrofit == null) d("NetManager not init")
        return retrofit
    }
}